/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package thitracnghiem;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author TienNT
 */
public class BoDeThi {

    String maMonThi;
    public ArrayList<CauHoi> mListCauHoi = new ArrayList<CauHoi>();

    public ArrayList<CauHoi> getListCauHoi() {
        return mListCauHoi;
    }

    public BoDeThi(String maMonThi) {
        this.maMonThi = maMonThi;
        getAllCauHoi();
    }
    static Connection conn;
    static Statement stm;

    public static void openDatabase() throws SQLException {
        conn = DriverManager.getConnection("jdbc:odbc:ttn");
        stm = conn.createStatement();
    }

    public static void closeDatabase() throws SQLException {
        stm.close();
        conn.close();
    }

    private void getAllCauHoi() {
        try {
            openDatabase();
            String query = "select macauhoi, cauhoi, dapan from CauHoi where mamonthi = '" + maMonThi + "'";
            ResultSet rs = stm.executeQuery(query);
            if (rs.next()) {
                do {
                    String maCauHoi = rs.getString("macauhoi");
                    String cauhoi = rs.getString("cauhoi");

                    String dapan = rs.getString("dapan");
                    mListCauHoi.add(new CauHoi(maCauHoi, maMonThi, cauhoi, getCauTraLoi(maCauHoi), dapan));
                } while (rs.next());
            }
            closeDatabase();
        } catch (SQLException ex) {
            Logger.getLogger(BoDeThi.class.getName()).log(Level.SEVERE, null, ex);
        } finally{
            
        }

    }

    private ArrayList<CauTraLoi> getCauTraLoi(String maCauHoi) {
        ArrayList<CauTraLoi> result = new ArrayList<CauTraLoi>();
        try {
            openDatabase();
            String query = "select malc, luachon from CauTraLoi where macauhoi = '" + maCauHoi + "'";
            ResultSet rs = stm.executeQuery(query);
            if (rs.next()) {
                do {
                    String malc = rs.getString("malc");
                    String noidung = rs.getString("luachon");
                    result.add(new CauTraLoi(maCauHoi, malc, noidung));
                } while (rs.next());
                return result;
            }
            closeDatabase();
        } catch (SQLException ex) {
            Logger.getLogger(BoDeThi.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
        return null;
    }
}
